package com.hotel.front.controller.company;

import com.hotel.comm.service.company.ICompanyUserService;
import com.hotel.front.bean.Constants;
import com.hotel.front.bean.FieldValidatorResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * Created by frank on 15-7-1.
 */
@Controller
public class LoginController {

    private static final Logger LOGGER = LoggerFactory.getLogger(CompanyUserController.class);

    @Autowired
    ICompanyUserService companyUserService;

    //随机码
//    public static final char[] ranlist = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    public static final char[] ranlist = "0123456789".toCharArray();

    /**
     * 绘制验证码
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/randomCode")
    public void getRandomCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int randomNumber = 4;
        // 图片宽度
        int width = 70;
        // 图片高度
        int height = 30;
        StringBuilder sb = new StringBuilder();
        Random randomer = new Random();
        for (int i = 0; i < randomNumber; i++) {
            sb.append(ranlist[randomer.nextInt(ranlist.length)]);
        }
        // 保存到session中
        HttpSession session = req.getSession();
        session.setAttribute(Constants.RANDOM_IN_SESSION, sb.toString());

        // 画画
        // 创建一个图片对象
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_BGR);

        // 得到图片对象对应的绘画缓存,绘画都在Graphics对象上
        Graphics g = image.getGraphics();

        // 绘制背景
        g.setColor(Color.WHITE);
        // 填充矩形
        g.fillRect(0, 0, width, height);

        // 绘制边框
        g.setColor(Color.DARK_GRAY);
        g.drawRect(0, 0, width - 1, height - 1);
        // 绘制文字
        g.setColor(Color.BLACK);
        g.setFont(new Font("宋体", Font.ITALIC, 25));
        g.drawString(sb.toString(), 7, height - 6);

        //绘制干扰点
        for (int i = 0; i < 300; i++) {
            g.fillRect(randomer.nextInt(width - 1),
                    randomer.nextInt(height - 1), 1, 1);
        }
        // 关闭绘画资源
        g.dispose();

        //清除图片缓存：IE7  firefox验证码没有反应问题
        //设定网页的到期时间，一旦过期则必须到服务器上重新调用
        resp.setDateHeader("Expires", -1);
        //Cache-Control指定请求和响应遵循的缓存机制   no-cache指示请求或响应消息不能缓存
        resp.setHeader("Cache-Control", "no-cache");
        //是用于设定禁止浏览器从本地机的缓存中调阅页面内容，设定后一旦离开网页就无法从Cache中再调出
        resp.setHeader("Pragma", "no-cache");

        // 输出
        ImageIO.write(image, "JPG", resp.getOutputStream());
    }

    /**
     * 验证码检查
     *
     * @param randomCode
     * @param request
     * @return
     */
    @RequestMapping(value = "/checkRandomCode")
    @ResponseBody
    public FieldValidatorResponse checkValidRandomCode(@RequestParam(value = "randomCode") String randomCode, HttpServletRequest request) {
        FieldValidatorResponse remoteFieldValidatorResponse = new FieldValidatorResponse();
        remoteFieldValidatorResponse.setValid(true);
        String randomCodeStore = (String) request.getSession().getAttribute(Constants.RANDOM_IN_SESSION);

        //验证码验证
        if (!StringUtils.equals(randomCode, randomCodeStore)) {
            remoteFieldValidatorResponse.setValid(false);
        }
        return remoteFieldValidatorResponse;
    }

    /**
     * 用户登出
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/login_out_user")
    public String loginOutUser(HttpServletRequest request) {
        request.getSession().invalidate();
        return Constants.INDEX;
    }

}
